#!/bin/bash

# Web Notes 重新部署脚本 - 修复API URL和Nginx配置
set -e

echo "🚀 开始重新部署 Web Notes (修复版本)..."

# 配置
PROJECT_DIR="/var/www/web-notes"
WEB_ROOT="/var/www/html"
BACKUP_DIR="/var/www/backups"
NGINX_SITES="/etc/nginx/sites-available"

# 检查权限
if [[ $EUID -ne 0 ]]; then
   echo "❌ 此脚本需要 root 权限运行"
   echo "请使用: sudo ./redeploy-fixed.sh"
   exit 1
fi

# 创建备份目录
mkdir -p $BACKUP_DIR

echo "📦 停止当前服务..."
pm2 stop all || true
pm2 delete all || true

echo "📁 进入项目目录..."
cd $PROJECT_DIR

echo "🔧 验证环境配置..."
if [ ! -f "web-notes-frontend/.env.production" ]; then
    echo "创建生产环境配置文件..."
    cat > web-notes-frontend/.env.production << EOF
# 生产环境API配置 - 使用Nginx反向代理
# 后端路由已包含/api前缀，所以这里使用空字符串
VITE_API_BASE_URL=
EOF
else
    echo "更新生产环境配置文件..."
    cat > web-notes-frontend/.env.production << EOF
# 生产环境API配置 - 使用Nginx反向代理
# 后端路由已包含/api前缀，所以这里使用空字符串
VITE_API_BASE_URL=
EOF
fi

echo "📝 显示当前API配置:"
cat web-notes-frontend/.env.production

echo "🔨 重新构建后端..."
cd web-notes-backend
npm install
npm run build

echo "🎨 重新构建前端..."
cd ../web-notes-frontend
npm install
npm run build

echo "💾 备份当前文件..."
if [ -d "$WEB_ROOT" ]; then
    cp -r $WEB_ROOT $BACKUP_DIR/html.backup.$(date +%Y%m%d_%H%M%S)
fi

echo "📤 部署新的前端文件..."
rm -rf $WEB_ROOT/*
cp -r dist/* $WEB_ROOT/
chown -R www-data:www-data $WEB_ROOT/
chmod -R 755 $WEB_ROOT/

echo "⚙️  更新Nginx配置..."
# 备份当前Nginx配置
if [ -f "$NGINX_SITES/web-notes" ]; then
    cp $NGINX_SITES/web-notes $BACKUP_DIR/nginx.backup.$(date +%Y%m%d_%H%M%S)
fi

# 复制新的Nginx配置
cp $PROJECT_DIR/nginx-config/web-notes.conf $NGINX_SITES/web-notes

# 确保配置链接存在
if [ ! -L "/etc/nginx/sites-enabled/web-notes" ]; then
    ln -sf $NGINX_SITES/web-notes /etc/nginx/sites-enabled/web-notes
fi

echo "🔍 测试Nginx配置..."
nginx -t

if [ $? -eq 0 ]; then
    echo "✅ Nginx配置测试通过"
    echo "🔄 重新加载Nginx..."
    systemctl reload nginx
else
    echo "❌ Nginx配置测试失败，恢复备份..."
    if [ -f "$BACKUP_DIR/nginx.backup.$(date +%Y%m%d_%H%M%S)" ]; then
        cp $BACKUP_DIR/nginx.backup.$(date +%Y%m%d_%H%M%S) $NGINX_SITES/web-notes
        systemctl reload nginx
    fi
    exit 1
fi

echo "🚀 启动后端服务..."
cd $PROJECT_DIR/web-notes-backend
pm2 start dist/index.js --name "web-notes-api"

echo "⏳ 等待服务启动..."
sleep 5

echo "🔍 验证部署..."
echo ""
echo "=== PM2 状态 ==="
pm2 status

echo ""
echo "=== 后端健康检查 ==="
if curl -s http://localhost:3000/health > /dev/null; then
    echo "✅ 后端服务正常运行"
    curl -s http://localhost:3000/health | jq . || curl -s http://localhost:3000/health
else
    echo "❌ 后端服务连接失败"
fi

echo ""
echo "=== 端口监听状态 ==="
netstat -tlnp | grep :3000 || echo "❌ 端口3000未监听"

echo ""
echo "=== Nginx 状态 ==="
systemctl status nginx --no-pager -l

echo ""
echo "=== API 代理测试 ==="
if curl -s http://localhost/api/health > /dev/null; then
    echo "✅ Nginx 代理正常工作"
    curl -s http://localhost/api/health | jq . || curl -s http://localhost/api/health
else
    echo "❌ Nginx 代理测试失败"
fi

echo ""
echo "=== 前端文件检查 ==="
if [ -f "$WEB_ROOT/index.html" ]; then
    echo "✅ 前端文件部署成功"
    ls -la $WEB_ROOT/ | head -10
else
    echo "❌ 前端文件部署失败"
fi

echo ""
echo "🎉 重新部署完成！"
echo ""
echo "📋 重要信息:"
echo "  🌐 网站地址: http://your-server-ip/"
echo "  🔗 API地址: http://your-server-ip/api/"
echo "  📊 PM2监控: pm2 monit"
echo "  📝 查看日志: pm2 logs web-notes-api"
echo ""
echo "🧪 测试步骤:"
echo "  1. 打开浏览器访问您的网站"
echo "  2. 按F12打开开发者工具控制台"
echo "  3. 查看API URL应该显示: 📡 最终 API URL: /api"
echo "  4. 尝试登录功能"
echo ""
echo "🔧 如果还有问题，请检查:"
echo "  - 浏览器控制台的错误信息"
echo "  - Nginx错误日志: tail -f /var/log/nginx/web-notes-error.log"
echo "  - PM2日志: pm2 logs web-notes-api"